package com.yuanchu.order.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.yuanchu.common.exception.YuanChuException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;

import java.io.Serializable;

/**
 * @version: 1.0
 * @Author: adan
 * @description: 获取当前用户身份工具类
 * @date: 2024-01-15 22:02
 */
@Slf4j
// @Component
public class SecurityUtil {
    public static YoshopStoreUserEntity getUser() {
        try {
            Object principalObj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principalObj instanceof String) {
                //取出用户身份信息
                String principal = principalObj.toString();
                //将json转成对象
                YoshopStoreUserEntity user = JSON.parseObject(principal, YoshopStoreUserEntity.class);
                return user;
            }
        } catch (Exception e) {
            log.error("获取当前登录用户身份出错:{}", e.getMessage());
            e.printStackTrace();
        }

        return null;
    }
    public static Integer getUserId() {
        try {
            Object principalObj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principalObj instanceof String) {
                //取出用户身份信息
                String principal = principalObj.toString();
                //将json转成对象
                YoshopStoreUserEntity user = JSON.parseObject(principal, YoshopStoreUserEntity.class);
                return user.getStoreUserId();
            }
        } catch (Exception e) {
            log.error("获取当前登录用户身份出错:{}", e.getMessage());
            e.printStackTrace();
            throw new YuanChuException("获取当前登录用户身份出错");
        }

        return null;
    }

    @Data
    public static class YoshopStoreUserEntity implements Serializable {
        private static final long serialVersionUID = 1L;

        /**
         * 主键ID
         */
        @TableId
        private Integer storeUserId;
        /**
         * 用户名
         */
        @JsonProperty("username")
        private String userName;
        /**
         * 登录密码
         */
        private String password;
        /**
         * 姓名
         */
        private String realName;
        /**
         * 是否为超级管理员
         */
        private Integer isSuper;
        /**
         * 是否删除
         */
        private Integer isDelete;
        /**
         * 排序(数字越小越靠前)
         */
        private Integer sort;
        /**
         * 商城ID
         */
        private Integer storeId;
        /**
         * 创建时间
         */
        private Integer createTime;
        /**
         * 更新时间
         */
        private Integer updateTime;


    }
}
